import os
import re
import json
import csv
from . import admin, db
from flask import request, jsonify
from .models import User, Group, Link
from flask_admin import BaseView, expose
from flask_admin.contrib.sqla import ModelView
from flask_admin.contrib.fileadmin import FileAdmin
from flask_admin.contrib.sqla.ajax import QueryAjaxModelLoader, DEFAULT_PAGE_SIZE

class FilteredAjaxModelLoader(QueryAjaxModelLoader):
    additional_filters = []

    def get_list(self, term, offset=0, limit=DEFAULT_PAGE_SIZE):
        filters = list(
            field.ilike(u'%%%s%%' % term) for field in self._cached_fields
        )
        for f in self.additional_filters:
            filters.append(f)
        # filters.append(User.list_id == 2) # Now this is passed in the constructor
        # filters.append(User.is_active == 'Y')
        return (
            db.session.query(self.model)
                .filter(*filters)
                .all()
        )

    def __init__(self, name, session, model, **options):
        super(FilteredAjaxModelLoader, self).__init__(name, session, model, **options)
        self.additional_filters = options.get('filters')


# Group View
class GroupView(ModelView):
    page_size = 10
    can_view_details = True
    can_delete = True
    create_modal = True
    edit_modal = True
    column_display_pk = True
    column_searchable_list = ['title', 'user.username']
    column_filters = []
    form_columns = ['title', 'user']
    column_list = ['id', 'title', 'user.username',
                   'create_time', 'update_time']
    column_labels = form_labels = {
        'id': 'ID',
        'title': '分组名',
        'user': '用户名',
        'user.username': '用户名',
        'create_time': '创建时间',
        'update_time': '更新时间'
    }
    column_formatters = {
        'create_time': lambda v, c, m, n: m.create_time.strftime("%Y-%m-%d %H:%M:%S"),
        'update_time': lambda v, c, m, n: m.update_time.strftime("%Y-%m-%d %H:%M:%S")
    }
    form_ajax_refs = {
        'user': {
            'fields': (User.username, ),
            'minimum_input_length': 0,
            'placeholder': '请选择',
            'page_size': 10
        }
    }


# Link View
class LinkView(ModelView):
    page_size = 10
    can_view_details = True
    create_modal = True
    edit_modal = True
    column_display_pk = True
    column_searchable_list = ['title']
    column_filters = []
    form_columns = ['title', 'url', 'desc', 'user', 'group']
    column_list = ['id', 'title', 'user.username', 'group.title', 'create_time', 'update_time']
    column_labels = form_labels = {
        'id': 'ID',
        'user': '用户名',
        'group': '分组名',
        'title': '名称',
        'url': '链接',
        'desc': '描述',
        'user.username': '用户名',
        'group.title': '分组名',
        'create_time': '创建时间',
        'update_time': '更新时间'
    }
    column_formatters = {
        # 'progress': lambda v, c, m, n: '{}%'.format(m.progress),
    }
    form_ajax_refs = {
        'group': FilteredAjaxModelLoader('group', db.session, Group, fields=['title'],
                                filters=[Group.uid == '2'], page_size=10, minimum_input_length=0),
        'user': {
            'fields': (User.username, ),
            'placeholder': '请选择',
            'minimum_input_length': 0,
            'page_size': 10
        }
    }


class UserView(ModelView):
    page_size = 10
    can_view_details = True
    can_delete = can_edit = True
    create_modal = True
    edit_modal = True
    column_display_pk = True
    form_columns = ['username', 'password', 'nickname', 'phone', 'email']
    column_list = form_columns + ['lastest_login_time']
    column_searchable_list = ['username', 'nickname']
    column_labels = form_labels = {
        'id': 'ID',
        'username': '用户名',
        'password': '密码',
        'nickname': '昵称',
        'email': '邮箱',
        'phone': '手机号',
        'lastest_login_time': '最后登录时间'
    }
    column_formatters = {
        'phone': lambda v, c, m, n: re.sub("(\d{3})(\d{4})(\d{3})", r'\g<1>****\g<3>', m.phone),
        'lastest_login_time': lambda v, c, m, n: m.lastest_login_time.strftime("%Y-%m-%d %H:%M:%S")
    }


user_view = UserView(User, db.session, "用户管理")
group_view = GroupView(Group, db.session, "分组管理")
link_view = LinkView(Link, db.session, "链接管理")

# all views
__all__ = ['user_view', 'group_view', 'link_view']
